package com.hankarun.gevrek.lib;

import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.nntp.NNTPClient;

import com.hankarun.gevrek.GroupActivity;
import com.hankarun.gevrek.LoginActivity;
import com.hankarun.gevrek.R;
import com.hankarun.gevrek.WidgetActivity;
import com.hankarun.gevrek.lib.ServerManager.MySSLSocketFactory;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class GevrekWidgetProvider extends AppWidgetProvider{
	public static String YOUR_AWESOME_ACTION = "YourAwesomeAction";

	public static long getGroupCount(String _group,String _username, String _password){
		NNTPClient client = new NNTPClient();
		if(_group.equals(""))
			return -1;
		else{
			String returns = null;
			try {
				client.setSocketFactory(new MySSLSocketFactory());
				client.connect("news.ceng.metu.edu.tr",563);
				client.authenticate(_username, _password);
				client.group(_group);
				returns = client.getReplyString();	
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				Log.e("get",e.getMessage());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e("get",e.getMessage());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.e("get",e.toString());
			}
				 
			if(returns!=null){
				String[] codes = returns.split(" ");
				long count = Long.parseLong(codes[3]);
				return count;
			}
			return -1;
		}
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (intent.getAction().equals("android.appwidget.action.APPWIDGET_UPDATE_OPTIONS")) {
		Bundle extras = intent.getExtras();
		   if(extras!=null) {
			    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
			    ComponentName thisAppWidget = new ComponentName(context.getPackageName(), GevrekWidgetProvider.class.getName());
			    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

			    onUpdate(context, appWidgetManager, appWidgetIds);			
		   }
		}
		if(intent.getAction().equals(YOUR_AWESOME_ACTION)){
			//Set update to the zero
			Bundle extras = intent.getExtras();
			int appWidgetId = 0;
			if(extras != null)
            {
				appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,0);
				String current = WidgetActivity.getPrefCount(context, appWidgetId);
				WidgetActivity.setCount(context, appWidgetId, current);
				
				AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
			    ComponentName thisAppWidget = new ComponentName(context.getPackageName(), GevrekWidgetProvider.class.getName());
			    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

			    onUpdate(context, appWidgetManager, appWidgetIds);
            }				        		
			
			//Start new intent
			Intent myInt = new Intent();
			myInt.setClass(context, LoginActivity.class);
			myInt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(myInt);
		}
		/*
		 *         
		 */
	 }
    
    
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // For each widget that needs an update, get the text that we should display:
        //   - Create a RemoteViews object for it
        //   - Set the text in the RemoteViews object
        //   - Tell the AppWidgetManager to show that views object for the widget.
        ComponentName thisWidget = new ComponentName(context,GevrekWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

        // Build the intent to call the service
        Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

        // Update the widgets via the service
        context.startService(intent);    	  
    }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // When the user deletes the widget, delete the preference associated with it.
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
        	WidgetActivity.delPref(context, appWidgetIds[i]);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // When the first widget is created, register for the TIMEZONE_CHANGED and TIME_CHANGED
        // broadcasts.  We don't want to be listening for these if nobody has our widget active.
        // This setting is sticky across reboots, but that doesn't matter, because this will
        // be called after boot if there is a widget instance for this provider.
    }

    @Override
    public void onDisabled(Context context) {
        // When the first widget is created, stop listening for the TIMEZONE_CHANGED and
        // TIME_CHANGED broadcasts.
    }

    public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
            int appWidgetId, String[] vars) {
        Intent intents = new Intent(context, GevrekWidgetProvider.class);

        intents.setAction(YOUR_AWESOME_ACTION);
        intents.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
        		appWidgetId, intents, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.widgetcount, pendingIntent);
        views.setOnClickPendingIntent(R.id.widgetname, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
        if(vars[2]!=null){
	     	DownloadGroup task = new DownloadGroup(context,appWidgetId,vars);
	 		task.execute();
        }
    }
    
	public static class UpdateWidgetService extends Service{
	    @Override
	    public void onStart(Intent intent, int startId) {
	    	AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());

	    	int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
	    	
	        final int N = appWidgetIds.length;
	        if(N == 0)
	        	stopSelf();
	        for (int i=0; i<N; i++) {
	            int appWidgetId = appWidgetIds[i];
	            String[] vars = WidgetActivity.loadPref(this.getApplicationContext(), appWidgetId);

	            
	            updateAppWidget(this.getApplicationContext(), appWidgetManager, appWidgetId, vars);
	        }
	        stopSelf();
	    }
	    
		
		@Override
		public IBinder onBind(Intent arg0) {
			return null;
		}
	}
	
	public static class DownloadGroup extends AsyncTask<Void,Void,Long>{

		Context context;
		Integer appWidgetId;
		AppWidgetManager appWidgetManager;
		String[] vars;
		
		public DownloadGroup(Context _context, Integer _appWidgetId, String[] _vars){
			context = _context;
			appWidgetId = _appWidgetId;
			vars = _vars;
			this.appWidgetManager = AppWidgetManager.getInstance(context);
		}
		
		@Override
		protected void onPostExecute(Long group) {
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
			WidgetActivity.setPrefCount(context, appWidgetId, String.valueOf(group));
	        if(vars[2]!=null){
		        if(vars[5].equals("-1")){
		        	vars[5] = String.valueOf(group);
		        	WidgetActivity.setPref(context, appWidgetId, vars);
		        	group = (long) 0;
		        }else{
		        	long pref = Long.parseLong(vars[5]);
		        	group = group - pref;
		        }
	        }						
			views.setTextViewText(R.id.widgetcount, "("+group+")");
	        String name = vars[3];
	        if(name == null){
	        	name = vars[2];
	        	if(name != null){
			    	if(name.length() > 14){
			    		name = "..."+name.substring(name.length()-11, name.length());
			    	}
	        	}
	        }
	        
	        views.setTextViewText(R.id.widgetname, name);
			appWidgetManager.updateAppWidget(appWidgetId, views);
	    }
		
		@Override
		protected Long doInBackground(Void... arg0) {
			return getGroupCount(vars[2], vars[0], vars[1]);
		}
		
	}
}
